package io.kimmking.dubbo.common.unit;

import java.util.function.Consumer;
import java.util.function.Function;

@FunctionalInterface
public interface ThrowableActionV0 {

    /**
     * Executes the action
     *
     * @throws Throwable if met with error
     */
    void execute() throws Throwable;

    default void finalExecute() throws Throwable {
    };

    /**
     * Executes {@link ThrowableActionV1}
     *
     * @param action {@link ThrowableActionV1}
     * @throws RuntimeException wrap {@link Exception} to {@link RuntimeException}
     */
    static void execute(ThrowableActionV1 action) throws RuntimeException {
        try {
            action.execute();
        }catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Executes {@link ThrowableActionV1}
     *
     * @param action {@link ThrowableActionV1}
     * @throws RuntimeException wrap {@link Exception} to {@link RuntimeException}
     */
    static void execute(ThrowableActionV1 action, Consumer<Throwable> errorHandler) {
        try {
            action.execute();
        }catch (Throwable e) {
            errorHandler.accept(e);
        }
    }

    /**
     * Executes {@link ThrowableActionV1}
     *
     * @param action {@link ThrowableActionV1}
     * @throws RuntimeException wrap {@link Exception} to {@link RuntimeException}
     */
    static void execute(ThrowableActionV1 action, Function<Throwable, Throwable> errorHandler) throws Throwable {
        try {
            action.execute();
        }catch (Throwable e) {
            throw errorHandler.apply(e);
        }finally {
//            finalExecute();
        }
    }

}
